<template>
  <div>
    <!-- 搜索栏 -->
    <el-form
      :model="searchForm.data"
      label-width="auto"
      :ref="searchForm.ref"
      @submit.prevent="searchForm.onSubmit"
    >
      <el-form-item>
        <el-col :span="6">
          <el-form-item
            label="用户名称:"
            prop="name"
          >
            <el-input
              v-model="searchForm.data.name"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          style="margin-left: 16px;"
        >
          <el-button
            type="primary"
            @click="searchForm.onSubmit"
          >
            <template #icon>
              <Search />
            </template>搜索</el-button>
          <el-button @click="searchForm.onClear">
            <template #icon>
              <Refresh />
            </template>重置</el-button>

        </el-col>
      </el-form-item>
      <el-form-item v-permission="['sys:usermgr:account:add']">
        <el-button
          @click="onAdd"
          type="success"
        >
          <template #icon>
            <Plus />
          </template>新增</el-button>
      </el-form-item>
    </el-form>
    <FormDialog
      ref="dialogRef"
      :formFields="fields"
      :formHandlers="formHandlers"
      @success="onDialogSuccess"
    />
    <PTable
      :dataColumns="fields"
      :table="table"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { FormMode, GenderRatioOptions, GenderToString } from '@/common/type/baseEnum'
import FormDialog from '@/components/FormDialog.vue'
import { addUserInfo, deleteUserInfo, editUserInfo, getRoleInfo, getUserInfo } from '@/api/usermgr'
import PTable from '@/components/PTable.vue'
import { DefaultPagTable, type PagTable } from '@/common/type/table'
import type { UserData } from '@/common/type/data'
import Logger from '@/util/log'
import { ElMessage } from 'element-plus'
import { isResultSuccess } from '@/util/http'
import type { SearchForm } from '@/common/type/form'
import type { CommonField, SelectOptions } from '@/common/type/field'
// 搜索框
const searchForm: SearchForm = {
  data: reactive({
    name: '',
  }),

  ref: ref(),
  onSubmit: () => {
    console.log('search submit!', searchForm.data.name)
    table.initTableData()
  },
  onClear: () => {
    searchForm.ref.value.resetFields()
    table.initTableData()
  },
}

// 新增按钮
const dialogRef = ref()
const roleList = ref<SelectOptions[]>([])

const fields: CommonField[] = [
  {
    prop: 'idx',
    label: '序号',
    formMeta: {
      hideInForm: true,
    },
    tableMeta: {
      width: '66',
      type: 'index'
    },
  },
  {
    label: '用户名称',
    prop: 'account',
    formMeta: {
      type: 'text',
      placeholder: '可作为登录账号',
      rules: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
      disabledOn: [FormMode.Edit]
    },
    tableMeta: {
      width: '160',
    }
  },
  {
    label: '昵称',
    prop: 'nickname',
    formMeta: {
      type: 'text',
    },
    tableMeta: {
      width: '160',
    }
  },
  {
    label: '电子邮箱',
    prop: 'email',
    formMeta: {
      placeholder: '可作为登录账号',
      rules: [
        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
        { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }
  },
  {
    label: '性别',
    prop: 'gender',
    formMeta: {
      type: 'radio',
      rules: [{ required: true, message: '请选择性别', trigger: 'blur' }],
      options: GenderRatioOptions
    },
    tableMeta: {
      width: '80',
      formatter(row, column, cellValue, index) {
        return GenderToString[cellValue]
      },
    }
  },
  {
    label: '手机号码',
    prop: 'phone',
    formMeta: {
      placeholder: '可作为登录账号',
      rules: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            const phoneReg = /^1[3-9]\d{9}$/
            return phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号码'))
          },
          trigger: 'blur'
        }
      ]
    }
  },
  {
    label: '密码',
    prop: 'password',
    formMeta: {
      isPwd: true,
      rules: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      hideOn: [FormMode.Edit]
    },
    tableMeta: {
      hideInTable: true,
    }
  },
  {
    label: '确认密码',
    prop: 'confirmPassword',
    formMeta: {
      isPwd: true,
      rules: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            const passwordValue = dialogRef.value?.form?.data?.password  // 通过对话框引用获取密码值
            return value !== passwordValue ? callback(new Error('两次输入密码不一致')) : callback()
          },
          trigger: 'blur'
        }
      ],
      hideOn: [FormMode.Edit]
    },
    tableMeta: {
      hideInTable: true,
    }
  },
  {
    prop: 'role_name',
    label: '角色',
    formMeta: {
      type: 'multi-select',
      options: roleList.value,
      rules: [
        { required: true, message: '请输入角色', trigger: 'blur' },
      ],
    },
    tableMeta: {
      width: '200',
      contentType: 'tags',
    }
  },
  {
    prop: 'is_active',
    label: '是否启用',
    formMeta: {
      type: 'radio',
      rules: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
      options: [
        { label: '启用', value: 0 },
        { label: '禁用', value: 1 }
      ]
    },
    tableMeta: {
      width: '90',
      contentType: 'tag',
      tagMapper: {
        0: { text: '可用', type: 'success' },
        1: { text: '禁用', type: 'danger' }
      },
      // formatter(row, column, cellValue, index) {
      //   return cellValue === 0 ? '可用' : '禁用'
      // },
    }
  },
  {
    label: '创建时间',
    prop: 'created_at',
    formMeta: {
      hideInForm: true,
    },
    tableMeta: {
      formatter(row, column, cellValue, index) {
        return cellValue.replace('T', ' ').slice(0, 19)
      }
    }
  }
]

const formHandlers = new Map([
  [FormMode.Add, addUserInfo],
  [FormMode.Edit, editUserInfo],
])

const onDialogSuccess = () => {
  table.initTableData()
}

const onAdd = () => {
  dialogRef.value.open(FormMode.Add)
}

const table: PagTable<UserData> = new DefaultPagTable({
  refreshTableData: async () => {
    try {
      const res = await getUserInfo({
        pageNo: table.pagination?.currentPage as number,
        pageSize: table.pagination?.pageSize,
        userName: searchForm.data.name ? searchForm.data.name : undefined
      })
      Logger.prettyInfo('getUserInfo', res)
      if (res && isResultSuccess(res)) {
        table.data.splice(0, table.data.length, ...res.data.list)
        table.pagination.total = res.data.total || res.data.list?.length
      }
    } catch (error) {
      Logger.prettyError('getUserInfo catch error', error)
    }
  },
  onTableDataEdit: (index: number, row: UserData) => {
    dialogRef.value.open(FormMode.Edit, row)
  },
  editPermissionCode: 'sys:usermgr:account:edit',
  deletePermissionCode: 'sys:usermgr:account:delete',
  onTableDataDelete: async (index: number, row: UserData) => {
    Logger.prettyInfo('deleteRoleInfo', row)
    let success = false, errMsg: any
    try {
      const res = await deleteUserInfo({ "account": row.account })
      success = isResultSuccess(res)
      errMsg = res.msg
    } catch (error) {
      errMsg = error
      Logger.prettyError('deleteRoleInfo catch error', error.response.data)
    }
    if (!success) {
      ElMessage.error('删除角色失败！' + errMsg)
    } else {
      ElMessage.success('删除角色成功！')
      table.initTableData()
    }
  }
})

onMounted(async () => {
  const res = await getRoleInfo()
  if (res && isResultSuccess(res)) {
    res.data.list.forEach((item: any) => {
      roleList.value.push({
        label: item.name,
        value: item.name
      })
    })
    // Logger.prettyInfo('getRoleInfo', res.data, roleList.value)
  }
})
</script>

<style scoped></style>
